using System.Collections;
using System.Linq;
using UnityEngine;

public class WaveManager : MonoBehaviour
{
    [SerializeField] private GameObject _bossPrefab;
    [SerializeField] private GameObject _statScrollPrefab;
    [SerializeField] private WaveData[] allWave;

    private int _currentWaveIndex;
    private Coroutine _spawnEnemyCoroutine;
    private void OnEnable()
    {
        EventCenter.AddEventListener(EventName.PlayerDead, HandlePlayerDead);
        EventCenter.AddEventListener(EventName.StartRougeGame, StartRougeGame);
        EventCenter.AddEventListener(EventName.LeaveRougeGame, StopRougeGame);
    }
    private void OnDisable()
    {
        EventCenter.RemoveEventListener(EventName.PlayerDead, HandlePlayerDead);
        EventCenter.RemoveEventListener(EventName.StartRougeGame, StartRougeGame);
        EventCenter.RemoveEventListener(EventName.LeaveRougeGame, StopRougeGame);
    }
    public void Start()
    {
        _currentWaveIndex = 0;
    }
    public void StartRougeGame()
    {
        StartCoroutine(StartNextWaveCo());
    }
    public void StopRougeGame()
    {
        StopAllCoroutines();
    }
    private IEnumerator StartNextWaveCo()
    {
        if (_currentWaveIndex >= allWave.Length)
        {
            Debug.Log("---------- 所有波次已生成完毕 ----------");
            yield break;
        }

        WaveData currentWave = allWave[_currentWaveIndex];

        //波次开始前的延迟
        //TODO执行后续逻辑///////////////////////////////////////////////////////
        yield return new WaitForSeconds(currentWave.waveStartDelay);

        _spawnEnemyCoroutine = StartCoroutine(SpawnWaveEnemiesCo(currentWave));

        yield return _spawnEnemyCoroutine;
    }

    private IEnumerator SpawnWaveEnemiesCo(WaveData currentWaveData)
    {
        EventCenter.TriggerEvent(EventName.UI_UpdateWaveInfo, currentWaveData);

        float timer = 0;
        WaitForSeconds waitForSeconds = new(currentWaveData.spawnInterval);
        if (currentWaveData.waveFinishCondition == WaveFinishCondition.EndTime)
        {
            while (timer < currentWaveData.waveDuration)
            {
                timer += currentWaveData.spawnInterval;

                for (int i = 0; i < currentWaveData.enemySpawnDatas.Length; i++)
                    for (int j = 0; j < currentWaveData.enemySpawnDatas[i].enemyCount; j++)
                        EventCenter.TriggerEvent(EventName.SpawnEnemy, currentWaveData.enemySpawnDatas[i].enemyPrefab);

                yield return waitForSeconds;
            }
        }
        else if (currentWaveData.waveFinishCondition == WaveFinishCondition.BeatBoss)
        {
            EventCenter.TriggerEvent(EventName.SpawnEnemy, _bossPrefab);
            while (true)
            {
                for (int i = 0; i < currentWaveData.enemySpawnDatas.Length; i++)
                    EventCenter.TriggerEvent(EventName.SpawnEnemy, currentWaveData.enemySpawnDatas[i].enemyPrefab);

                yield return waitForSeconds;
            }
        }

        Debug.Log("---------- 当前波次结束 -----------");

        _currentWaveIndex++;

        EventCenter.TriggerEvent(EventName.CurrentWaveFinish);

        yield return new WaitForSeconds(currentWaveData.waveOverDelay);

        SpawnStatScroll();

        yield return new WaitForSeconds(currentWaveData.nextWaveWaitInterval);

        yield return StartCoroutine(StartNextWaveCo());
    }
    private void HandlePlayerDead()
    {
        StopAllCoroutines();
    }
    public void StopSpawnInBossDead()
    {
        if (_spawnEnemyCoroutine != null)
        {
            // 强制终止协程（循环会立即停止）
            StopCoroutine(_spawnEnemyCoroutine);
            _spawnEnemyCoroutine = null;
        }

        //TODO执行后续逻辑///////////////////////////////////////////////////////
    }
    private void SpawnStatScroll()
    {
        Transform player = Player.Instance.transform;

        float randomX = player.position.x + Random.Range(-3f, 3f);
        float randomY = player.position.y + Random.Range(-3f, 3f);
        Instantiate(_statScrollPrefab, new Vector2(randomX, randomY), Quaternion.identity);
    }
}
